package com.znyj.cloud.chain.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.multipart.Attribute;
import io.netty.handler.codec.http.multipart.DefaultHttpDataFactory;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;
import io.netty.util.CharsetUtil;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * Created by gaoliwei on 15-1-14.
 */
public class HttpUtil {

    public static FullHttpResponse getResponse(HttpResponseStatus status, String contentType, String content) {
        ByteBuf contentByteBuffer = Unpooled.copiedBuffer(content, CharsetUtil.UTF_8);
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, contentByteBuffer);
        response.headers().set(CONTENT_TYPE, contentType);
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

        return response;
    }

    public static FullHttpResponse getJsonResponse(HttpResponseStatus status, String content) {
        return getResponse(status, "text/json", content);
    }

    public static FullHttpResponse getJsonResponse(String content) {
        return getJsonResponse(OK, content);
    }

    public static FullHttpResponse getDefaultJsonSuccessResponse(JSONObject json) {
        return getJsonResponse(json.toString());
    }

    public static FullHttpResponse getDefaultJsonFailResponse(JSONObject json) {
        return getJsonResponse(json.toString());
    }

    public static Map<String, List<String>> getPostParams(HttpRequest request) {
        HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), request);
        List<InterfaceHttpData> datas = decoder.getBodyHttpDatas();

        Map<String, List<String>> result = new HashMap<String, List<String>>();
        for (InterfaceHttpData data : datas) {
            if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) {
                Attribute attribute = (Attribute) data;
                String name = attribute.getName();
                String value = null;
                try {
                    value = attribute.getValue();
                } catch (IOException e) {
                    continue;
                }

                if (result.containsKey(name)) {
                    List<String> values = result.get(name);
                    values.add(value);
                    result.put(name, values);
                } else {
                    List<String> values = new ArrayList<String>();
                    values.add(value);
                    result.put(name, values);
                }
            }
        }
        return result;
    }

    public static Map<String, List<String>> getGetParams(HttpRequest request) {
        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri());
        Map<String, List<String>> params = queryStringDecoder.parameters();
        return params;
    }

//    public static Map<String, List<String>> getParams(HttpRequest request) {
//        if (request.getMethod() == HttpMethod.GET) {
//            return getGetParams(request);
//        } else if (request.getMethod() == HttpMethod.POST) {
//            return getPostParams(request);
//        } else {
//            return new HashMap<String, List<String>>();
//        }
//    }

//    public static List<String> getParam(HttpRequest request, String param) {
//        if (request.getMethod() == HttpMethod.GET) {
//            return getGetParams(request).get(param);
//        } else if (request.getMethod() == HttpMethod.POST) {
//            return getPostParams(request).get(param);
//        } else {
//            return null;
//        }
//    }

    public static String getOneParam(HttpRequest request, String param) {
        List<String> params = null;
        if (request.getMethod() == HttpMethod.GET) {
            params = getGetParams(request).get(param);
        } else if (request.getMethod() == HttpMethod.POST) {
            params = getPostParams(request).get(param);
        } else {
            return null;
        }
        if (CollectionUtils.isEmpty(params)) {
            return null;
        }
        return params.get(0);
    }

//    public static JSONObject getJsonData(HttpRequest request) {
//        Map<String, List<String>> content = getParams(request);
//
//        if (!content.containsKey("hd_data")) {
//            return null;
//        }
//
//        String dataStr = content.get("hd_data").get(0);
//
//        JSONObject dataJson = JSON.parseObject(dataStr);
//
//        return dataJson;
//    }
//
//    public static JSONObject getResult(int code, String message, List<String> hexStrings) {
//        JSONObject result = new JSONObject();
//        result.put("code", code);
//        result.put("message", message);
//
//        JSONObject data = new JSONObject();
//        data.put("bytesList", hexStrings);
//        result.put("data", data);
//        return result;
//    }
//
//    public static JSONObject getResult(List<String> hexStrings) {
//        return getResult(0, "success", hexStrings);
//    }

}
